<template>
  <div class="post-card bg-white rounded-lg shadow-sm overflow-hidden">
    <!-- 作者信息 -->
    <div class="post-header flex items-center justify-between p-4">
      <div class="author-info flex items-center">
        <el-avatar
          :size="40"
          :src="post.author.avatar"
          class="cursor-pointer"
          @click="handleAuthorClick"
        />
        <div class="ml-3">
          <div
            class="font-medium cursor-pointer hover:text-primary-600"
            @click="handleAuthorClick"
          >
            {{ post.author.nickname }}
          </div>
          <div class="text-sm text-gray-500">
            {{ formatTime(post.createTime) }}
          </div>
        </div>
      </div>
      <el-dropdown trigger="click" @command="handleMoreCommand">
        <el-button type="text">
          <el-icon><More /></el-icon>
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="favorite">
              {{ post.isFavorited ? "取消收藏" : "收藏" }}
            </el-dropdown-item>
            <el-dropdown-item command="report">举报</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 内容区域 -->
    <div class="post-content px-4">
      <!-- 文本内容 -->
      <div class="text-content mb-4">
        <p class="text-gray-900 whitespace-pre-wrap">{{ post.content }}</p>
      </div>

      <!-- 话题标签 -->
      <div v-if="post.topics?.length" class="topics-list mb-4">
        <el-tag
          v-for="topic in post.topics"
          :key="topic.id"
          size="small"
          class="mr-2 cursor-pointer"
          @click="handleTopicClick(topic)"
        >
          #{{ topic.name }}
        </el-tag>
      </div>

      <!-- 位置信息 -->
      <div
        v-if="post.location"
        class="location text-sm text-gray-500 mb-4 flex items-center"
      >
        <el-icon><Location /></el-icon>
        <span class="ml-1">{{ post.location }}</span>
      </div>

      <!-- 媒体内容 -->
      <div v-if="post.media?.length" class="media-content mb-4">
        <!-- 单张图片/视频 -->
        <template v-if="post.media.length === 1">
          <div class="single-media" @click="handleMediaClick(post.media[0], 0)">
            <el-image
              v-if="isImage(post.media[0])"
              :src="post.media[0]"
              fit="cover"
              class="w-full rounded-lg cursor-zoom-in"
              :preview-src-list="post.media"
            />
            <video
              v-else
              :src="post.media[0]"
              class="w-full rounded-lg cursor-pointer"
              controls
            />
          </div>
        </template>

        <!-- 多张图片/视频网格 -->
        <template v-else>
          <div
            class="media-grid"
            :class="{
              'grid-2': post.media.length === 2,
              'grid-3': post.media.length === 3,
              'grid-4': post.media.length === 4,
              'grid-more': post.media.length > 4,
            }"
          >
            <div
              v-for="(media, index) in displayMedia"
              :key="index"
              class="media-item relative"
              @click="handleMediaClick(media, index)"
            >
              <el-image
                v-if="isImage(media)"
                :src="media"
                fit="cover"
                class="w-full h-full rounded-lg cursor-zoom-in"
                :preview-src-list="post.media"
              />
              <video
                v-else
                :src="media"
                class="w-full h-full rounded-lg object-cover cursor-pointer"
                @click.stop="playVideo($event)"
              />
              <!-- 更多媒体提示 -->
              <div
                v-if="index === 8 && post.media.length > 9"
                class="more-media absolute inset-0 bg-black bg-opacity-50 rounded-lg flex items-center justify-center text-white cursor-pointer"
              >
                +{{ post.media.length - 9 }}
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <!-- 互动区域 -->
    <div class="post-footer px-4 pb-4">
      <div
        class="interaction-bar flex items-center justify-between border-t border-gray-100 pt-4"
      >
        <!-- 点赞 -->
        <div
          class="action-item flex items-center cursor-pointer"
          @click="handleLikeClick"
        >
          <el-icon :class="{ 'text-primary-600': post.isLiked }">
            <component :is="post.isLiked ? 'Star' : 'StarFilled'" />
          </el-icon>
          <span class="ml-1" :class="{ 'text-primary-600': post.isLiked }">
            {{ post.likes || "点赞" }}
          </span>
        </div>

        <!-- 评论 -->
        <div
          class="action-item flex items-center cursor-pointer"
          @click="handleCommentClick"
        >
          <el-icon><ChatDotRound /></el-icon>
          <span class="ml-1">{{ post.comments || "评论" }}</span>
        </div>

        <!-- 分享 -->
        <div
          class="action-item flex items-center cursor-pointer"
          @click="handleShareClick"
        >
          <el-icon><Share /></el-icon>
          <span class="ml-1">{{ post.shares || "分享" }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useRouter } from "vue-router";
import {
  More,
  Star,
  StarFilled,
  ChatDotRound,
  Share,
  Location,
} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";

dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();

const props = defineProps({
  post: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["like", "comment", "share", "favorite", "report"]);

// 计算要显示的媒体内容（最多显示9个）
const displayMedia = computed(() => {
  return props.post.media?.slice(0, 9) || [];
});

// 判断是否为图片
const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url);
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).fromNow();
};

// 处理作者点击
const handleAuthorClick = () => {
  router.push(`/user/profile/${props.post.author.id}`);
};

// 处理话题点击
const handleTopicClick = (topic) => {
  router.push(`/topic/${topic.id}`);
};

// 处理媒体点击
const handleMediaClick = (media, index) => {
  if (isImage(media)) {
    // 图片预览由 el-image 组件自动处理
    return;
  }
  // 视频播放逻辑
  playVideo(event);
};

// 播放视频
const playVideo = (event) => {
  const video = event.target;
  if (video.paused) {
    video.play();
  } else {
    video.pause();
  }
};

// 处理更多操作
const handleMoreCommand = (command) => {
  switch (command) {
    case "favorite":
      emit("favorite", props.post);
      break;
    case "report":
      emit("report", props.post);
      break;
  }
};

// 处理点赞点击
const handleLikeClick = () => {
  emit("like", props.post);
};

// 处理评论点击
const handleCommentClick = () => {
  emit("comment", props.post);
};

// 处理分享点击
const handleShareClick = () => {
  emit("share", props.post);
};
</script>

<style lang="scss" scoped>
.post-card {
  @apply transition-all duration-300;

  &:hover {
    @apply shadow-md;
  }

  .media-content {
    .single-media {
      @apply max-h-[600px] overflow-hidden;

      :deep(img),
      video {
        @apply w-full h-full object-contain;
      }
    }

    .media-grid {
      @apply grid gap-2;

      &.grid-2 {
        @apply grid-cols-2;

        .media-item {
          @apply aspect-square;
        }
      }

      &.grid-3 {
        @apply grid-cols-3;

        .media-item {
          @apply aspect-square;
        }
      }

      &.grid-4 {
        @apply grid-cols-2;

        .media-item {
          @apply aspect-square;
        }
      }

      &.grid-more {
        @apply grid-cols-3;

        .media-item {
          @apply aspect-square;
        }
      }
    }
  }

  .interaction-bar {
    .action-item {
      @apply py-2 px-4 rounded-full transition-colors duration-200 hover:bg-gray-100;
    }
  }
}
</style>
